package servlet.admin;

import bean.Admin;
import bean.News;
import dao.AdminDAO;
import dao.NewsDAO;
import org.apache.commons.fileupload.FileItem;
import util.MultipartFormUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Servlet implementation class UpdateNews
 */
@WebServlet("/Update")
public class Update extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public Update() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 *
	 *      根据表单信息更新新闻，可部分更新
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		response.setCharacterEncoding("UTF-8");


		int id = Integer.valueOf(request.getParameter("id"));
		List<FileItem> formItems = MultipartFormUtil.getFormItems(request, response);

		Admin admin = new Admin();
		admin.setId(id);
		admin.setAdmin(false);

		List<String> list=new ArrayList<>();
		for (int i = 0; i < 4; i++) {
			String s = new String(formItems.get(i).getString().getBytes("ISO8859_1"), "utf-8");
			list.add(s);
		}

		admin.setSex(list.get(3));
		admin.setName(list.get(2));
		admin.setAccount(list.get(0));
		admin.setPwd(list.get(1));
		AdminDAO adminDAO = new AdminDAO();
		boolean success = adminDAO.updateAdmin(admin);
		request.setAttribute("success", success);
		response.sendRedirect("./jsp/manage/usersList.jsp");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
